/**
 * Author: Lily Jiang
 * Create Time: 2019/12/24
 * Description:
 */

import React from "react";
import { connect } from "react-redux";
import * as actions from "@/store/actions";
import './Index.scss'
import {Link} from "react-router-dom";
import ArticleItem from '../components/articleItem/Index.js'
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
import { Toast } from 'antd-mobile';

const AutoPlaySwipeableViews = autoPlay(SwipeableViews);

class Index extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            todayStr: '',
            zhMonth: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            todayInfo: {
                day: 0,
                month: '',
            },

            swiperList: [],
            swiperIndex: 0,

            list: {},
            noMore: false,
            pageNo: 1,
            pageSize: 10,
            uploading: false
        };
    }

    mainRef;

    componentDidMount() {
        this.initScroll()
        this.getSwiperInfo()
        this.getArticleList()
        this.getToday()
    }

    changeLoadingState = (status) => {
        this.props.dispatch(actions.updateAppSetting({
            appLoading: status
        }))
    }

    initScroll = () => {
        this.mainRef.addEventListener('scroll', () => {
            this.throttle(this.scrollHandler)
        }, false)
    }

    throttle = (fn) => {
        clearInterval(fn.tId)
        fn.tId = setTimeout(() => {
            fn()
        }, 300)
    }

    scrollHandler = () => {
        //  到达底部加载下一页
        if ((this.mainRef.clientHeight + this.mainRef.scrollTop) >= (this.mainRef.scrollHeight - 100)) {
            if (this.state.noMore || this.state.uploading) {
                return
            }

            this.setState({
                pageNo: this.state.pageNo + 1
            }, () => {
                this.getArticleList(this.state.pageNo)
            })
        }
    }

    getSwiperInfo = () => {
        React.$api.getHomeSwiper().then(data => {
            this.setState({
                swiperList: data || []
            })
        }, err => {
            err.msg && Toast.info(err.msg)
        })
    }

    getArticleList = (pageNo = 1) => {
        if (pageNo != 1) {
            this.setState({
                uploading: true
            })
        } else {
            this.changeLoadingState(true)
        }

        let list = this.state.list || {}

        React.$api.getArticleList({
            pageNo: pageNo,
            pageSize: this.state.pageSize
        }).then(data => {
            data.items.forEach(item => {
                let timeStr = item.create_time.slice(0, 10)

                if (!list[timeStr]) {
                    list[timeStr] = []
                }

                list[timeStr].push(item)
            })

            this.changeLoadingState(false)
            this.setState({
                list: list,
                noMore: data.items.length < this.state.pageSize ? true : false,
                uploading: false
            })
        }, err => {
            console.log(err)
            this.changeLoadingState(false)
            this.setState({
                uploading: false
            })
        })
    }

    getToday = () => {
        let today = new Date()
        let year = today.getFullYear()
        let month = today.getMonth() + 1
        let day = today.getDate()

        let todayStr = `${year}-${month > 9 ? month : '0' + month}-${day > 9 ? day : '0' + day}`

        this.setState({
            todayStr: todayStr,
            todayInfo: {
                day: day,
                month: this.state.zhMonth[month - 1]
            }
        })
    }

    onChangeIndex = (index, indexLatest, meta) => {
        this.setState({
            swiperIndex: index
        })
    }

    goArticleDetail = (info) => {
        window.location.hash = '#/article/detail?articleId=' + info.id
    }

    render() {
        return (
            <div className="app-container df-col page-index">
                <div className="header ubb_1px">
                    <div className="time">
                        <p className="fs20">{this.state.todayInfo.day}</p>
                        <p className="fs12">{this.state.todayInfo.month}</p>
                    </div>
                    <div className="title df1">知乎日报</div>
                    <Link to="/user/index">
                        <img src={(this.props.userInfo && this.props.userInfo.head_img) || require('../../assets/images/default/default_head.png')} alt="" className="header-img"/>
                    </Link>
                </div>

                <div className="main df1 of-y-a" ref={(com) => this.mainRef = com}>
                    {/*swiper*/}
                    {
                        this.state.swiperList.length ? (
                            <div className="swiper-wrap">
                                <AutoPlaySwipeableViews onChangeIndex={this.onChangeIndex}>
                                    {
                                        this.state.swiperList.map(item => {
                                            return (
                                                <div className="w-1-1 aspectratio swiper" key={item.id.toString()}>
                                                    <div className="aspectratio-content swiper-item"
                                                         style={{backgroundImage: `url(${item.picture})`}} onClick={(e) => this.goArticleDetail(item)}>
                                                        <div className="info">
                                                            <div className="title">{item.picture_title || item.title || ''}</div>
                                                            <div className="author">作者 / {item.user.username}</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            )
                                        })
                                    }
                                </AutoPlaySwipeableViews>
                                <div className="swiper-page">
                                    {
                                        this.state.swiperList.map((item, index) => {
                                            return (
                                                <div key={index.toString()} className={'swiper-page-item ' + (index === this.state.swiperIndex ? 'active' : '')}></div>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        ): ''
                    }


                    {/*article list*/}
                    <div className="list-wrap">
                        {
                            JSON.stringify(this.state.list) !== '{}' ? Object.keys(this.state.list).map(timeStr => {
                                let items = this.state.list[timeStr]
                                let content = ''

                                if (this.state.todayStr !== timeStr) {
                                    content = (
                                        <div key={timeStr}>
                                            <div className="timeline">
                                                <span>{timeStr.slice(5, 10).replace('-', '月') + '号'}</span>
                                            </div>
                                            {items.map(item => {
                                                let articleItem = (<ArticleItem key={item.id.toString()} info={item}></ArticleItem>)

                                                return articleItem
                                            })}
                                        </div>
                                    )
                                } else {
                                    content = items.map(item => {
                                        let articleItem = (<ArticleItem key={item.id.toString()} info={item}></ArticleItem>)

                                        return articleItem
                                    })
                                }

                                return content
                            }) : null
                        }

                        <div className="padding12 tx-c">{this.state.noMore === true ? '内容已加载完毕' : ((JSON.stringify(this.state.list) !== '{}' && this.state.uploading) ? '加载中' : null)}</div>

                    </div>
                </div>
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        userInfo: state.app.user,
    }
}
export default connect(mapStateToProps)(Index)